package com.dartfar.base.action;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONArray;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.dartfar.base.model.Authority;
import com.dartfar.base.model.Function;
import com.dartfar.base.model.Role;
import com.dartfar.base.service.AuthorityService;
import com.dartfar.base.service.FunctionService;
import com.dartfar.base.service.RoleService;
import com.dartfar.base.vo.FunctionVo;
import com.dartfar.base.vo.TreeVo;
import com.dartfar.menu.model.Menu;
import com.dartfar.menu.service.MenuService;

/**
 * 权限Action对象
 * @author 王琦
 */
@Component("authorityAction")
@Scope("prototype")
public class AuthorityAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	static Logger logger = Logger.getLogger(AuthorityAction.class);
	
	/**
	 * Service对象
	 */
	private MenuService menuService;
	private RoleService roleService;
	private FunctionService functionService;
	private AuthorityService authorityService;
	

	/**
	 * 页面传参
	 */
	private int id;
	private String name;
	private int roleId;
	private int menuId;
	
	private String[] funArray;
	private List funList;
	private ArrayList funArr;
	
	private String functionIds;
	private String moduleIds;
	private String menuIds;
	private List<FunctionVo> functions;

	/**
	 * 页面跳转
	 */
	public String pl_List() {
		//获取权限列表
		functions = getAutFunctions();
		
		Role role = null;
		//如果页面调转时如果没有角色ID传值，默认取第一个角色
		if (roleId == 0) {
			role = roleService.getFirst();
			if (role != null) {
				roleId = role.getRoleId();
			}
		}
		return "pl_List";
	}
	
	
	/**
	 * 保存角色权限
	 */
	public String save(){
		
		logger.info("funArray：" + funArray);
		logger.info("moduleIds：" + moduleIds);
		
		
		//获取角色对象
		Role role = roleService.get(roleId);
		//获取菜单对象
		Menu menu = menuService.get(menuId);
		//保存权限
		authorityService.add(role, menu, functionIds);
		return SUCCESS;
	}
	
	
	public String delete(){
		authorityService.deleteByRoleId(roleId);
		return SUCCESS;
	}	
	
	public String loadFunctionDateTreeGrid(){
		List<Function> functions = functionService.getList();
		List<FunctionVo> functionVos = new ArrayList<FunctionVo>();
		
		for (Iterator<Function> i = functions.iterator(); i.hasNext();) {
			Function fun = i.next();
			FunctionVo functionVo = new FunctionVo();
			functionVo.setId(fun.getId());
			functionVo.setName(fun.getName());
			functionVo.setCode(fun.getCode());
			functionVo.setDes(fun.getDes());
			//functionVo.setChecked(true);
			functionVos.add(functionVo);
		}
		String jsonResult = JSONArray.fromObject(functionVos).toString();
		System.out.println("jsonResult: " + jsonResult);
		try {
			response.getWriter().write(jsonResult);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public String loadFunctionsDataByAut(){
		System.out.println("roleId: " + roleId);
		System.out.println("menuId: " + menuId);
		
		List<Authority> authoritys = authorityService.getListByRoleMenuId(null, roleId, menuId);
		List<FunctionVo> functionVos = new ArrayList<FunctionVo>();
		for (Iterator<Authority> i = authoritys.iterator(); i.hasNext();) {
			Authority aut = i.next();
			Function fun = aut.getFunction();
			FunctionVo functionVo = new FunctionVo();
			functionVo.setId(fun.getId());
			functionVo.setName(fun.getName());
			functionVo.setCode(fun.getCode());
			functionVo.setDes(fun.getDes());
			functionVos.add(functionVo);
		}
		
		String jsonResult = JSONArray.fromObject(functionVos).toString();
		System.out.println("jsonResult: " + jsonResult);
		try {
			response.getWriter().write(jsonResult);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	/**
	 * 读取权限树的模块和功能
	 * @return 权限树的Json字符串
	 */
	public String loadTreeData() {
		//主菜单VO对象
		List<TreeVo> treeMainMenuVos = new ArrayList<TreeVo>();
		try{
			//获取所有主菜单
			List<Menu> mainMenus = menuService.getMainMenuLsit();
			//获取所有功能
			List<Function> functions = functionService.getList();

			//循环主菜单
			for (Iterator<Menu> i = mainMenus.iterator(); i.hasNext();) {
				Menu menu = i.next();
				TreeVo treeMainMenuVo = new TreeVo();
				treeMainMenuVo.setId("m" + menu.getId());
				treeMainMenuVo.setText(menu.getName());
				treeMainMenuVo.setIconCls(menu.getIconCls());
				//如果主菜单中存在子菜单
				if (menuService.existSubMenuByMenuId(menu.getId())){
					treeMainMenuVo.setState("open");
					//获取根据主菜单ID获取子菜单列表
					List<Menu> subMenus = menuService.getSubMenuList(menu.getId());
					//子菜单树递归
					System.out.println("roleId: " + roleId);
					List<TreeVo> treeSubMenuVos = menus2Trees(subMenus, 0, functions, roleId);
					treeMainMenuVo.setChildren(treeSubMenuVos);
				}
				treeMainMenuVos.add(treeMainMenuVo);
			}
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		

		//转化为Json字符串
		String jsonResult = JSONArray.fromObject(treeMainMenuVos).toString();
		try {
			response.getWriter().write(jsonResult);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 子菜单递归
	 * @param functions 功能列表
	 * @param parentId 父结点ID
	 * @param roleFunctions 角色中的所有功能
	 * @return
	 */
	public List<TreeVo> menus2Trees(List<Menu> menus, int parentId,	List<Function> functions, int roleid) {
		List<TreeVo> treeVos = new ArrayList<TreeVo>();
		for (Iterator<Menu> i = menus.iterator(); i.hasNext();) {
			Menu menu = i.next();
			int menuParentId = 0;
			if (menu.getParentMenu() != null) {
				menuParentId = menu.getParentMenu().getId();
			}

			if (parentId == menuParentId) {
				TreeVo treeVo = new TreeVo();
				treeVo.setId("s" + menu.getId());
				treeVo.setText(menu.getName());
				treeVo.setIconCls(menu.getIconCls());
				//如果不是叶子节点，树结点打开
				if (!menu.isLeaf()) {
					treeVo.setState("open");
					//递归下级结点
					List<TreeVo> nextTreeVos = menus2Trees(menus, menu.getId(), functions, roleid);
					treeVo.setChildren(nextTreeVos);
				}else{
					treeVo.setState("closed");
					List<TreeVo> treeFunctionVos = functionTrees(functions, roleid, menu.getId());
					treeVo.setChildren(treeFunctionVos);
				}
				treeVos.add(treeVo);
			}
		}
		return treeVos;
	}
	/**
	 * 功能递归
	 * @param functions 功能列表
	 * @return
	 */
	public List<TreeVo> functionTrees(List<Function> functions, int roleid, int menuid) {
		//从SESSION中获取 功能列表
		Map functionMap = (Map)session.get("function");
		
		//根据菜单ID 获取 菜单拥有的功能
		List<Authority> autlist = authorityService.getListByRoleMenuId(null, roleid, menuid);
		
		List<TreeVo> treeVos = new ArrayList<TreeVo>();
		//循环功能列表
		for (Iterator<Function> i = functions.iterator(); i.hasNext();) {
			Function fun = i.next();
			TreeVo treeVo = new TreeVo();
			treeVo.setId("f" + fun.getId());
			treeVo.setText(fun.getDes());
			treeVo.setIconCls(fun.getIconCls());
			//遍历当前菜单拥有的功能权限
			if(autlist != null){
				for(Iterator<Authority> a = autlist.iterator();a.hasNext();){
					Authority aut = a.next();
					//如果功能ID存在菜单权限中，结点被选中
					if(aut.getFunction() != null){
						if(fun.getId() == aut.getFunction().getId() && aut.getMenu().getId() == menuid){
							treeVo.setChecked(true);
						}
					}
				}
			}
			
			treeVos.add(treeVo);
		}
		return treeVos;
	}

	
	/**
	 * Spring注入Service
	 */
	
	@Resource
	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}
	
	@Resource
	public void setMenuService(MenuService menuService) {
		this.menuService = menuService;
	}
	
	@Resource
	public void setFunctionService(FunctionService functionService) {
		this.functionService = functionService;
	}

	@Resource
	public void setAuthorityService(AuthorityService authorityService) {
		this.authorityService = authorityService;
	}


	/**
	 * Gets And Sets
	 */
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getRoleId() {
		return roleId;
	}

	public void setRoleId(int roleId) {
		this.roleId = roleId;
	}

	public String getFunctionIds() {
		return functionIds;
	}

	public void setFunctionIds(String functionIds) {
		this.functionIds = functionIds;
	}

	public String getModuleIds() {
		return moduleIds;
	}

	public void setModuleIds(String moduleIds) {
		this.moduleIds = moduleIds;
	}

	public String getMenuIds() {
		return menuIds;
	}

	public void setMenuIds(String menuIds) {
		this.menuIds = menuIds;
	}

	public int getMenuId() {
		return menuId;
	}

	public void setMenuId(int menuId) {
		this.menuId = menuId;
	}


	public List<FunctionVo> getFunctions() {
		return functions;
	}


	public void setFunctions(List<FunctionVo> functions) {
		this.functions = functions;
	}


	public String[] getFunArray() {
		return funArray;
	}


	public void setFunArray(String[] funArray) {
		this.funArray = funArray;
	}


	public List getFunList() {
		return funList;
	}


	public void setFunList(List funList) {
		this.funList = funList;
	}


	public ArrayList getFunArr() {
		return funArr;
	}


	public void setFunArr(ArrayList funArr) {
		this.funArr = funArr;
	}


	
}
